import type { SiteEntry, UserProfile, UserSettings, PasswordTemplate, AppState, GeneratedPassword } from './types';
import { MPW, initializeMPW } from './mpw';

export class PasswordManager {
  private state: AppState;
  private listeners: Set<(state: AppState) => void> = new Set();
  private lockTimer: number | null = null;

  constructor() {
    this.state = {
      isLoggedIn: false,
      currentUser: null,
      mpwInstance: null,
      selectedSite: null,
      isLoading: false,
      error: null,
      showAddSite: false,
      showSettings: false
    };

    // 初始化 MPW 库
    initializeMPW();
  }

  // 状态管理
  subscribe(listener: (state: AppState) => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  private setState(updates: Partial<AppState>): void {
    this.state = { ...this.state, ...updates };
    this.listeners.forEach(listener => listener(this.state));
  }

  getState(): AppState {
    return { ...this.state };
  }

  // 用户认证
  async login(name: string, masterPassword: string): Promise<void> {
    this.setState({ isLoading: true, error: null });

    try {
      // 创建 MPW 实例
      const mpwInstance = new MPW(name, masterPassword) as any;

      // 测试密钥生成
      await mpwInstance.key;

      // 加载用户配置
      const userProfile = this.loadUserProfile(name);

      this.setState({
        isLoggedIn: true,
        currentUser: userProfile,
        mpwInstance,
        isLoading: false
      });

      this.startAutoLockTimer();
    } catch (error) {
      this.setState({
        isLoading: false,
        error: error instanceof Error ? error.message : '登录失败'
      });
      throw error;
    }
  }

  logout(): void {
    if (this.state.mpwInstance) {
      this.state.mpwInstance.invalidate();
    }

    if (this.lockTimer) {
      clearTimeout(this.lockTimer);
      this.lockTimer = null;
    }

    this.setState({
      isLoggedIn: false,
      currentUser: null,
      mpwInstance: null,
      selectedSite: null,
      showAddSite: false,
      showSettings: false
    });
  }

  // 自动锁定
  private startAutoLockTimer(): void {
    if (!this.state.currentUser?.settings.autoLock) return;

    if (this.lockTimer) {
      clearTimeout(this.lockTimer);
    }

    const timeout = this.state.currentUser.settings.autoLockTimeout * 60 * 1000;
    this.lockTimer = window.setTimeout(() => {
      this.logout();
    }, timeout);
  }

  resetAutoLockTimer(): void {
    if (this.state.isLoggedIn) {
      this.startAutoLockTimer();
    }
  }

  // 网站管理
  addSite(name: string, siteName: string, template: PasswordTemplate = 'long', context?: string): void {
    if (!this.state.currentUser) return;

    const newSite: SiteEntry = {
      id: this.generateId(),
      name,
      siteName,
      counter: 1,
      template,
      context,
      lastUsed: Date.now(),
      created: Date.now()
    };

    const updatedUser = {
      ...this.state.currentUser,
      sites: [...this.state.currentUser.sites, newSite]
    };

    this.setState({ currentUser: updatedUser, showAddSite: false });
    this.saveUserProfile(updatedUser);
  }

  updateSite(siteId: string, updates: Partial<SiteEntry>): void {
    if (!this.state.currentUser) return;

    const updatedSites = this.state.currentUser.sites.map(site =>
      site.id === siteId ? { ...site, ...updates, lastUsed: Date.now() } : site
    );

    const updatedUser = {
      ...this.state.currentUser,
      sites: updatedSites
    };

    this.setState({ currentUser: updatedUser });
    this.saveUserProfile(updatedUser);
  }

  deleteSite(siteId: string): void {
    if (!this.state.currentUser) return;

    const updatedSites = this.state.currentUser.sites.filter(site => site.id !== siteId);
    const updatedUser = {
      ...this.state.currentUser,
      sites: updatedSites
    };

    this.setState({
      currentUser: updatedUser,
      selectedSite: this.state.selectedSite?.id === siteId ? null : this.state.selectedSite
    });
    this.saveUserProfile(updatedUser);
  }

  selectSite(site: SiteEntry | null): void {
    this.setState({ selectedSite: site });
    this.resetAutoLockTimer();
  }

  // 密码生成
  async generatePassword(site: SiteEntry): Promise<GeneratedPassword> {
    if (!this.state.mpwInstance) {
      throw new Error('未登录');
    }

    try {
      const password = await this.state.mpwInstance.generateAuthentication(
        site.siteName,
        site.counter,
        site.context || '',
        site.template
      );

      // 更新最后使用时间
      this.updateSite(site.id, { lastUsed: Date.now() });

      return {
        password,
        site: site.siteName,
        template: site.template,
        counter: site.counter,
        generatedAt: Date.now()
      };
    } catch (error) {
      throw new Error(`密码生成失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  // UI 状态管理
  showAddSiteDialog(): void {
    this.setState({ showAddSite: true });
  }

  hideAddSiteDialog(): void {
    this.setState({ showAddSite: false });
  }

  showSettingsDialog(): void {
    this.setState({ showSettings: true });
  }

  hideSettingsDialog(): void {
    this.setState({ showSettings: false });
  }

  clearError(): void {
    this.setState({ error: null });
  }

  // 数据持久化
  private loadUserProfile(name: string): UserProfile {
    const key = `mpw_profile_${name}`;
    const stored = localStorage.getItem(key);

    if (stored) {
      try {
        const profile = JSON.parse(stored);
        return {
          ...profile,
          settings: {
            defaultTemplate: 'long',
            autoLock: true,
            autoLockTimeout: 15,
            showPassword: false,
            theme: 'auto',
            ...profile.settings
          }
        };
      } catch (error) {
        console.warn('加载用户配置失败:', error);
      }
    }

    // 返回默认配置
    return {
      name,
      sites: [],
      settings: {
        defaultTemplate: 'long',
        autoLock: true,
        autoLockTimeout: 15,
        showPassword: false,
        theme: 'auto'
      }
    };
  }

  private saveUserProfile(profile: UserProfile): void {
    const key = `mpw_profile_${profile.name}`;
    try {
      localStorage.setItem(key, JSON.stringify(profile));
    } catch (error) {
      console.error('保存用户配置失败:', error);
    }
  }

  updateSettings(settings: Partial<UserSettings>): void {
    if (!this.state.currentUser) return;

    const updatedUser = {
      ...this.state.currentUser,
      settings: { ...this.state.currentUser.settings, ...settings }
    };

    this.setState({ currentUser: updatedUser });
    this.saveUserProfile(updatedUser);

    // 重新启动自动锁定计时器
    if (settings.autoLock !== undefined || settings.autoLockTimeout !== undefined) {
      this.startAutoLockTimer();
    }
  }

  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substring(2);
  }

  // 获取密码模板信息
  getTemplateInfo(template: PasswordTemplate): { name: string; description: string; example: string } {
    const templates = {
      maximum: { name: '最大强度', description: '20个字符，包含所有字符类型', example: 'w6Jb@4rC9#kL8mN3$pQ7' },
      long: { name: '长密码', description: '14个字符，易记忆的格式', example: 'ZedaFaxcZaso9*' },
      medium: { name: '中等长度', description: '8个字符，平衡安全性和便利性', example: 'ZedFax4*' },
      basic: { name: '基础密码', description: '8个字符，仅字母和数字', example: 'zedfax94' },
      short: { name: '短密码', description: '4个字符，用于PIN码', example: 'Zed4' },
      pin: { name: '数字PIN', description: '4位数字', example: '9427' },
      name: { name: '用户名', description: '9个字符，适合用户名', example: 'zedfaxcas' },
      phrase: { name: '密码短语', description: '多个单词组成', example: 'zedf axc zaso cav' }
    };

    return templates[template] || templates.long;
  }
}
